package com.ruoyi.common;

import org.apache.http.*;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.protocol.HttpContext;
import java.net.URI;

/**
 * 支持POST重定向的自定义策略
 */
class PostRedirectStrategy extends DefaultRedirectStrategy {
    @Override
    public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode == HttpStatus.SC_TEMPORARY_REDIRECT ||
                statusCode == HttpStatus.SC_MOVED_TEMPORARILY;
    }

    @Override
    public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
        // 获取重定向地址
        URI uri = getLocationURI(request, response, context);

        // 保持原始请求方法
        RequestBuilder builder = RequestBuilder.create(request.getRequestLine().getMethod())
                .setUri(uri)
                .setVersion(response.getStatusLine().getProtocolVersion());

        // 复制原始请求头
        Header[] headers = request.getAllHeaders();
        for (Header header : headers) {
            if (!skipHeader(header)) {
                builder.addHeader(header);
            }
        }

        // 复制请求体（POST需要）
        if (request instanceof HttpEntityEnclosingRequest) {
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            builder.setEntity(entity);
        }

        return builder.build();
    }

    private boolean skipHeader(Header header) {
        return header.getName().equalsIgnoreCase("Content-Length") ||
                header.getName().equalsIgnoreCase("Host");
    }
}